package com.ms.base.comm.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <b>description</b>： <br>
 * <b>time</b>：2018-07-27 10:27 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class CostTimeFilter extends OncePerRequestFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CostTimeFilter.class);

    private CostTimeFilterProperties costTimeFilterProperties;

    public CostTimeFilter(CostTimeFilterProperties costTimeFilterProperties) {
        this.costTimeFilterProperties = costTimeFilterProperties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (this.costTimeFilterProperties != null && this.costTimeFilterProperties.isEnabled()) {
            long startTime = System.nanoTime();
            String requestURL = request.getRequestURL().toString();
            try {
                logger.info(String.format("本次请求start[%s]", requestURL));
                filterChain.doFilter(request, response);
            } catch (Exception e) {
                throw e;
            } finally {
                double costTime = ((double) (System.nanoTime() - startTime)) / 1000000.00;
                logger.info(String.format("本次请求end[%s]耗时(ms):%s", requestURL, costTime));
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
